<?php


namespace app\common\model;


use think\Model;

class UserBrokerageLogModel extends Model
{
    protected $name = 'user_brokerage_log';

    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'integer';

    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';

    // 追加属性
    protected $append = [

    ];




    /**
     * 用户-分销数据统计
     * @param int $user_id
     */
    public function getList($user_id)
    {
        try {
            $user = model('app\common\model\User')
                ->field('id,nickname,avatar,group_id')
                ->with(['group'])
                ->find($user_id);
            $user->avatar = full_url($user->avatar);

            // 累计佣金
            $total_brokerage = model('app\common\model\UserBrokerageLogModel')
                ->where(['to_user_id' => $user_id])
                ->sum('brokerage');
            // 推广人数
            $user_ids = model('app\common\model\User')
                ->where(['pid' => $user_id])
                ->column('id');
            $total_popularize_num = count($user_ids);
            // 推广单数
            $total_order_num = model('app\common\model\order\OrderModel')
                ->whereIn('user_id',$user_ids)
                ->where('is_burst_order',1)
                ->where('is_pay',1)
                ->count();

            // 推广用户
            $user_1_list = model('app\common\model\User')
                ->field('id,nickname,avatar,group_id,jointime')
                ->where(['pid' => $user_id,'group_id' => 1])
                ->select();
            foreach ($user_1_list as $row) {
                $row->avatar = full_url($row->avatar);
                $row->jointime = date('Y-m-d',$row->jointime);
                // 累计推广人数
                $user_1_ids = model('app\common\model\User')
                    ->where(['pid' => $row->id,'group_id' => 1])
                    ->column('id');
                $row->total_user = count($user_1_ids);
                // 累计佣金
                $user_1_total_brokerage = model('app\common\model\UserBrokerageLogModel')
                    ->whereIn('to_user_id',$user_1_ids)
                    ->sum('brokerage');
                $row->total_brokerage = $user_1_total_brokerage;
                // 累计推广订单
                $user_1_total_order_num = model('app\common\model\order\OrderModel')
                    ->whereIn('user_id',$user_1_ids)
                    ->where('is_burst_order',1)
                    ->where('is_pay',1)
                    ->count();
                $row->total_order_num = $user_1_total_order_num;
            }
            $user_group_1_data = [
                'total_user' => count($user_1_list),
                'list_user' => $user_1_list,
            ];

            // 推广门店
            $user_2_list = model('app\common\model\User')
                ->field('id,nickname,avatar,group_id,jointime')
                ->where(['pid' => $user_id,'group_id' => 2])
                ->select();
            foreach ($user_2_list as $row) {
                $row->avatar = full_url($row->avatar);
                $row->jointime = date('Y-m-d',$row->jointime);
                // 累计推广人数
                $user_2_ids = model('app\common\model\User')
                    ->where(['pid' => $row->id,'group_id' => 2])
                    ->column('id');
                $row->total_user = count($user_2_ids);
                // 累计佣金
                $user_2_total_brokerage = model('app\common\model\UserBrokerageLogModel')
                    ->whereIn('to_user_id',$user_2_ids)
                    ->sum('brokerage');
                $row->total_brokerage = $user_2_total_brokerage;
                // 累计推广订单
                $user_2_total_order_num = model('app\common\model\order\OrderModel')
                    ->whereIn('user_id',$user_2_ids)
                    ->where('is_burst_order',1)
                    ->where('is_pay',1)
                    ->count();
                $row->total_order_num = $user_2_total_order_num;
            }
            $user_group_2_data = [
                'total_user' => count($user_2_list),
                'list_user' => $user_2_list,
            ];

            // 推广分公司
            $user_3_list = model('app\common\model\User')
                ->field('id,nickname,avatar,group_id,jointime')
                ->where(['pid' => $user_id,'group_id' => 3])
                ->select();
            foreach ($user_3_list as $row) {
                $row->avatar = full_url($row->avatar);
                $row->jointime = date('Y-m-d',$row->jointime);
                // 累计推广人数
                $user_3_ids = model('app\common\model\User')
                    ->where(['pid' => $row->id,'group_id' => 3])
                    ->column('id');
                $row->total_user = count($user_3_ids);
                // 累计佣金
                $user_3_total_brokerage = model('app\common\model\UserBrokerageLogModel')
                    ->whereIn('to_user_id',$user_3_ids)
                    ->sum('brokerage');
                $row->total_brokerage = $user_3_total_brokerage;
                // 累计推广订单
                $user_3_total_order_num = model('app\common\model\order\OrderModel')
                    ->whereIn('user_id',$user_3_ids)
                    ->where('is_burst_order',1)
                    ->where('is_pay',1)
                    ->count();
                $row->total_order_num = $user_3_total_order_num;
            }
            $user_group_3_data = [
                'total_user' => count($user_3_list),
                'list_user' => $user_3_list,
            ];

            $data = [
                'user' => $user,
                'total_brokerage' => $total_brokerage,
                'total_popularize_num' => $total_popularize_num,
                'total_order_num' => $total_order_num,
                'user_group_1_data' => $user_group_1_data,
                'user_group_2_data' => $user_group_2_data,
                'user_group_3_data' => $user_group_3_data,
            ];

            return [
                'code' => 200,
                'msg' => '请求成功',
                'data' => $data
            ];
        }catch (\Exception $e) {
            return [
                'code' => $e->getCode(),
                'msg' => $e->getMessage(),
                'data' => $e->getLine()
            ];
        }
    }


    /**
     * 用户-分销数据统计2
     * @param int $user_id
     * @param int $group_id
     */
    public function getList2($user_id,$group_id)
    {
        try {
            $user = model('app\common\model\User')
                ->field('id,nickname,avatar,group_id')
                ->with(['group'])
                ->find($user_id);
            $user->avatar = full_url($user->avatar);

            // 累计佣金
            $total_brokerage = model('app\common\model\UserBrokerageLogModel')
                ->where(['to_user_id' => $user_id])
                ->sum('brokerage');
            // 推广人数
            $user_ids = model('app\common\model\User')
                ->where(['pid' => $user_id])
                ->column('id');
            $total_popularize_num = count($user_ids);
            // 推广单数
            $total_order_num = model('app\common\model\order\OrderModel')
                ->whereIn('user_id',$user_ids)
                ->where('is_burst_order',1)
                ->where('is_pay',1)
                ->count();

            // 推广用户数
            $user_1_count = model('app\common\model\User')
                ->field('id,nickname,avatar,group_id,jointime')
                ->where(['pid' => $user_id,'group_id' => 1])
                ->count();
            // 推广门店数
            $user_2_count = model('app\common\model\User')
                ->field('id,nickname,avatar,group_id,jointime')
                ->where(['pid' => $user_id,'group_id' => 2])
                ->count();
            // 推广分公司数
            $user_3_count = model('app\common\model\User')
                ->field('id,nickname,avatar,group_id,jointime')
                ->where(['pid' => $user_id,'group_id' => 3])
                ->count();

            // 推广用户
            $list = model('app\common\model\User')
                ->field('id,nickname,avatar,group_id,jointime')
                ->where(['pid' => $user_id,'group_id' => $group_id])
                ->select();
            foreach ($list as $row) {
                $row->avatar = full_url($row->avatar);
                $row->jointime = date('Y-m-d',$row->jointime);
                // 累计推广人数
                $user_ids = model('app\common\model\User')
                    ->where(['pid' => $row->id,'group_id' => $group_id])
                    ->column('id');
                $row->total_user = count($user_ids);
                // 累计佣金
                $user_total_brokerage = model('app\common\model\UserBrokerageLogModel')
                    ->whereIn('to_user_id',$user_ids)
                    ->sum('brokerage');
                $row->total_brokerage = $user_total_brokerage;
                // 累计推广订单
                $user_total_order_num = model('app\common\model\order\OrderModel')
                    ->whereIn('user_id',$user_ids)
                    ->where('is_burst_order',1)
                    ->where('is_pay',1)
                    ->count();
                $row->total_order_num = $user_total_order_num;
            }

            $data = [
                'user' => $user,
                'total_brokerage' => $total_brokerage,
                'total_popularize_num' => $total_popularize_num,
                'total_order_num' => $total_order_num,
                'list' => $list,
                'user_1_count' => $user_1_count,
                'user_2_count' => $user_2_count,
                'user_3_count' => $user_3_count,
            ];

            return [
                'code' => 200,
                'msg' => '请求成功',
                'data' => $data
            ];
        }catch (\Exception $e) {
            return [
                'code' => $e->getCode(),
                'msg' => $e->getMessage(),
                'data' => $e->getLine()
            ];
        }
    }


    /**
     * 用户-分销数据统计3
     * @param $user_id
     * @param $group_id
     * @return array
     */
    public function getList3($user_id, $group_id): array
    {
        try {
            $user = model('app\common\model\User')
                ->field('id,nickname,avatar,group_id')
                ->with(['group'])
                ->find($user_id);
            $user->avatar = full_url($user->avatar);
            $user_relation = model('app\common\model\UserRelationModel')->get(['user_id' => $user_id]);
            $user_relation_group_field = "user_id_{$user_relation->group_id}";
            $p_user = [];
            if($user_relation->group_id < 4){
                $user_relation_parent_group_field = "user_id_" . ($user_relation->group_id + 1);
                $p_user = model('app\common\model\User')
                    ->field('id,nickname,avatar,group_id')
                    ->with(['group'])
                    ->find($user_relation["{$user_relation_parent_group_field}"]);
            }
            // 累计佣金/积分
            $total_brokerage = model('app\common\model\UserBrokerageLogModel')
                ->where('to_user_id',$user_id)
                ->sum('brokerage');
            // 累计推广人数
            $user_ids = model('app\common\model\UserRelationModel')
                ->where('group_id',$group_id)
                ->where($user_relation_group_field,$user_id)
                ->column('user_id');
            //$total_popularize_num = count($user_ids);
            $total_popularize_num = model('app\common\model\UserRelationModel')
                ->where('p_user_id',$user_id)
                ->count();
            // 累计推广单数
            $user_brokerage_order_ids = model('app\common\model\UserBrokerageLogModel')
                ->where('to_user_id',$user_id)
                ->column('order_id');
            $total_order_num = count(array_unique($user_brokerage_order_ids));

            $list = model('app\common\model\User')
                ->field('id,nickname,avatar,group_id,jointime')
                ->whereIn('id',$user_ids)
                ->select();
            foreach ($list as $row) {
                $row->avatar = full_url($row->avatar);
                $row->jointime = date('Y-m-d',$row->jointime);
                // 累计佣金/积分
                $user_total_brokerage = model('app\common\model\UserBrokerageLogModel')
                    ->where('to_user_id',$row->id)
                    ->sum('brokerage');
                $row->total_brokerage = $user_total_brokerage;
                // 累计推广人数
                $user_relation_child_group_field = "user_id_{$row->group_id}";
                $user_ids = model('app\common\model\UserRelationModel')
                    ->where('group_id','<=',$row->group_id)
                    ->where($user_relation_child_group_field,$row->id)
                    ->column('user_id');
                $row->total_user = count($user_ids);
                // 累计推广单数
                $user_brokerage_order_ids = model('app\common\model\UserBrokerageLogModel')
                    ->where('to_user_id',$row->id)
                    ->column('order_id');
                $row->total_order_num = count(array_unique($user_brokerage_order_ids));
            }

            // 推广用户数
            $user_1_count = model('app\common\model\UserRelationModel')
                ->where('group_id',1)
                ->where($user_relation_group_field,$user_id)
                ->count();
            // 推广门店数
            $user_2_count = model('app\common\model\UserRelationModel')
                ->where('group_id',2)
                ->where($user_relation_group_field,$user_id)
                ->count();
            // 推广分公司数
            $user_3_count = model('app\common\model\UserRelationModel')
                ->where('group_id',3)
                ->where($user_relation_group_field,$user_id)
                ->count();

            $data = [
                // 当前用户数据
                'user' => $user,
                // 当前上级用户数据
                'p_user' => $p_user,
                // 累计推广佣金/积分
                'total_brokerage' => $total_brokerage,
                // 累计推广人数
                'total_popularize_num' => $total_popularize_num,
                // 累计推广单数
                'total_order_num' => $total_order_num,
                // 推广列表
                'list' => $list,
                // 推广用户数
                'user_1_count' => $user_1_count,
                // 推广门店数
                'user_2_count' => $user_2_count,
                // 推广分公司数
                'user_3_count' => $user_3_count,
            ];

            return [
                'code' => 200,
                'msg' => '请求成功',
                'data' => $data
            ];
        }catch (\Exception $e) {
            return [
                'code' => $e->getCode(),
                'msg' => $e->getMessage(),
                'data' => $e->getLine()
            ];
        }
    }

    /**
     * 用户-分销数据统计4
     * @param $user_id
     * @return array
     */
    public function getList4($user_id)
    {
        try {
            $user = model('app\common\model\User')
                ->field('id,pid,nickname,avatar,group_id')
                ->with(['group'])
                ->find($user_id);
            $user->avatar = full_url($user->avatar);
            $p_user = model('app\common\model\User')
                ->field('id,nickname,avatar,group_id')
                ->with(['group'])
                ->find($user->pid);
            if($p_user){
                $p_user->avatar = full_url($p_user->avatar);
            }
            // 累计佣金/积分
            $total_brokerage = model('app\common\model\UserBrokerageLogModel')
                ->where('to_user_id',$user_id)
                ->sum('brokerage');
            // 累计推广人数
            $total_popularize_num = model('app\common\model\User')
                ->where('pid',$user_id)
                ->count();
            // 累计推广单数
            $user_brokerage_order_ids = model('app\common\model\UserBrokerageLogModel')
                ->where('to_user_id',$user_id)
                ->column('order_id');
            $total_order_num = count(array_unique($user_brokerage_order_ids));
            // 累计销售量(件)
            $total_order_goods_num = model('app\common\model\UserRelationModel')->where(['user_id' => $user_id])->value('num');
            // 推广人列表
            $list = model('app\common\model\User')
                ->field('id,pid,nickname,avatar,group_id,jointime')
                ->with(['group'])
                ->where('pid',$user_id)
                ->select();
            foreach ($list as $row) {
                $row->avatar = full_url($row->avatar);
                $row->jointime = date('Y-m-d',$row->jointime);
                // 累计佣金/积分
                $user_total_brokerage = model('app\common\model\UserBrokerageLogModel')
                    ->where('to_user_id',$row->id)
                    ->sum('brokerage');
                $row->total_brokerage = $user_total_brokerage;
                // 累计推广人数
                $row->total_user = model('app\common\model\User')
                    ->where('pid',$row->id)
                    ->count('id');
                // 累计推广单数
                $user_brokerage_order_ids = model('app\common\model\UserBrokerageLogModel')
                    ->where('to_user_id',$row->id)
                    ->column('order_id');
                $row->total_order_num = count(array_unique($user_brokerage_order_ids));
                // 累计销售量(件)
                $row->total_order_goods_num = model('app\common\model\UserRelationModel')->where(['user_id' => $row->id])->value('num');
            }

            $data = [
                // 当前用户数据
                'user' => $user,
                // 当前上级用户数据
                'p_user' => $p_user,
                // 累计推广佣金/积分
                'total_brokerage' => $total_brokerage,
                // 累计推广人数
                'total_popularize_num' => $total_popularize_num,
                // 累计推广单数
                'total_order_num' => $total_order_num,
                // 累计销售量(件)
                'total_order_goods_num' => $total_order_goods_num,
                // 推广列表
                'list' => $list,
            ];

            return [
                'code' => 200,
                'msg' => '请求成功',
                'data' => $data
            ];
        }catch (\Exception $e) {
            return [
                'code' => $e->getCode(),
                'msg' => $e->getMessage(),
                'data' => $e->getLine()
            ];
        }
    }


    /**
     * 分销处理
     * @param string $mold 类型:order=下单,exchange=兑换券
     * @param int $user_id 下单用户ID
     * @param int $order_id 订单ID
     * @param int $claim_shop_id 取货店铺[公司]ID/购买店铺[公司]ID
     * @param int $user_coupon_exchange_id 用户兑换券
    */
    static public function checkUserBrokerage($mold, $user_id, $order_id, $claim_shop_id = 0, $user_coupon_exchange_id = 0)
    {
        $system = model('app\common\model\SystemModel')->get(1);
        //佣金-推荐首单奖励(百分比)
        $brokerage_index_order = $system->brokerage_index_order / 100;
        //佣金-门店提货奖励(百分比)
        $brokerage_shop_claim = $system->brokerage_shop_claim / 100;
        //佣金积分转换比(1:X)
        $brokerage_score_conversion_rate = $system->brokerage_score_conversion_rate;
        //开启用户积分奖励:0=否,1=是
        $is_user_score_award = $system->is_user_score_award;
        // 分销次数
        $num = 0;
        // 当前用户, 当下单人身份为用户时(group_id==1), 才触发分销
        $from_user = model('app\common\model\User')->get($user_id);
        if($from_user->group_id != 1) {
            return false;
        }
        switch ($mold) {
            case 'order':
                // 判断是不是首单
                $order_count = model('app\common\model\order\OrderModel')
                    ->where(['user_id' => $user_id,'is_pay' => 1])
                    ->whereNull('deletetime')
                    ->count();
                if($order_count > 1) {
                    return false;
                }
                // 获取下单用户绑定关系,当用户未绑定上级,则没有绑定关系数据
                $user_relation = model('app\common\model\UserRelationModel')->get(['user_id' => $user_id]);
                if(!$user_relation) {
                    return false;
                }
                // 目标订单金额
                $order = model('app\common\model\order\OrderModel')->get($order_id);
                $amount = $order->pay_price;
                // 首单推荐佣金
                $brokerage = $amount * $brokerage_index_order;
                // 判断上级用户是否存在
                if($user_relation->user_id_1 > 0) {
                    // 开启用户积分奖励:0=否,1=是
                    if($is_user_score_award == 1) {
                        $to_user = model('app\common\model\User')->get($user_relation->user_id_1);
                        if($to_user && $to_user->group_id == 1){
                            // 首单推荐积分
                            $score = $brokerage * $brokerage_score_conversion_rate;
                            // 上级是用户,发放积分
                            $create_arr = [
                                'mold' => $mold,
                                'mold2' => 'score',
                                'from_user_group_id' => $from_user->group_id,
                                'from_user_id' => $from_user->id,
                                'to_user_group_id' => $to_user->group_id,
                                'to_user_id' => $to_user->id,
                                'order_id' => $order_id,
                                'amount' => $amount,
                                'brokerage' => $score,
                                'createtime' => time(),
                            ];
                            // 创建佣金记录
                            $user_brokerage_log_id = model('app\common\model\UserBrokerageLogModel')->insertGetId($create_arr);
                            $create_arr['id'] = $user_brokerage_log_id;
                            // 增加积分
                            \app\common\model\User::score($score, $to_user->id, '推荐首单奖励1', JsonEn($create_arr));
                            $num += 1;
                        }
                    }
                }
                // 判断上级门店是否存在
                if($user_relation->user_id_2 > 0) {
                    $to_user = model('app\common\model\User')->get($user_relation->user_id_2);
                    if($to_user && $to_user->group_id == 2) {
                        // 上级是门店,发放佣金
                        $create_arr = [
                            'mold' => $mold,
                            'mold2' => 'brokerage',
                            'from_user_group_id' => $from_user->group_id,
                            'from_user_id' => $from_user->id,
                            'to_user_group_id' => $to_user->group_id,
                            'to_user_id' => $to_user->id,
                            'order_id' => $order_id,
                            'amount' => $amount,
                            'brokerage' => $brokerage,
                            'createtime' => time(),
                        ];
                        // 创建佣金记录
                        $user_brokerage_log_id = model('app\common\model\UserBrokerageLogModel')->insertGetId($create_arr);
                        $create_arr['id'] = $user_brokerage_log_id;
                        // 增加佣金
                        \app\common\model\User::money($brokerage, $to_user->id, '推荐首单奖励2', JsonEn($create_arr));
                        $num += 1;
                    }
                }
                // 判断上级分公司是否存在
                if($user_relation->user_id_3 > 0 && $num < 2) {
                    $to_user = model('app\common\model\User')->get($user_relation->user_id_3);
                    if($to_user && $to_user->group_id == 3) {
                        if($num == 0) {
                            $brokerage += $brokerage;
                        }
                        // 上级是分公司,发放佣金
                        $create_arr = [
                            'mold' => $mold,
                            'mold2' => 'brokerage',
                            'from_user_group_id' => $from_user->group_id,
                            'from_user_id' => $from_user->id,
                            'to_user_group_id' => $to_user->group_id,
                            'to_user_id' => $to_user->id,
                            'order_id' => $order_id,
                            'amount' => $amount,
                            'brokerage' => $brokerage,
                            'createtime' => time(),
                        ];
                        // 创建佣金记录
                        $user_brokerage_log_id = model('app\common\model\UserBrokerageLogModel')->insertGetId($create_arr);
                        $create_arr['id'] = $user_brokerage_log_id;
                        // 增加佣金
                        \app\common\model\User::money($brokerage, $to_user->id, '推荐首单奖励3', JsonEn($create_arr));
                    }
                }

                break;
            case 'exchange':
                // 兑换券
                $user_coupon_exchange = model('app\common\model\UserCouponExchangeModel')->get($user_coupon_exchange_id);
                // 来源订单
                //$order = model('app\common\model\order\OrderModel')->get($order_id);
                $order_goods = model('app\common\model\order\OrderGoodsModel')
                    ->where(['order_id' => $order_id,'goods_id' => $user_coupon_exchange->goods_id,'goods_spec_id' => $user_coupon_exchange->goods_spec_id])
                    ->find();
                // 目标计算金额 = 商品单价 * 兑换券包含商品数量
                $amount = $order_goods->price * $user_coupon_exchange->goods_num;
                // 提货佣金
                $brokerage = $amount * $brokerage_shop_claim;
                // 取货门店分佣
                // 取货门店/公司
                $to_user = model('app\common\model\User')->get($claim_shop_id);
                if($to_user) {
                    $create_arr = [
                        'mold' => $mold,
                        'mold2' => 'brokerage',
                        'from_user_group_id' => $from_user->group_id,
                        'from_user_id' => $from_user->id,
                        'to_user_group_id' => $to_user->group_id,
                        'to_user_id' => $to_user->id,
                        'order_id' => $order_id,
                        //'claim_shop_id' => $claim_shop_id,
                        'user_coupon_exchange_id' => $user_coupon_exchange_id,
                        'amount' => $amount,
                        'brokerage' => $brokerage,
                        'createtime' => time(),
                    ];
                    $user_brokerage_log_id = model('app\common\model\UserBrokerageLogModel')->insertGetId($create_arr);
                    $create_arr['id'] = $user_brokerage_log_id;
                    // 增加佣金
                    \app\common\model\User::money($brokerage, $to_user->id, '用户兑换产品佣金', JsonEn($create_arr));
                }

                break;
        }

    }


    /**
     * 分销处理
     * Tip: 先处理升级, 再处理分销
     *
     * @param int $user_id 下单用户ID
     * @param int $order_id 订单ID
     */
    static public function checkUserBrokerage2($user_id, $order_id)
    {
        $order = model('app\common\model\order\OrderModel')->get($order_id);
        if(!$order || $order->is_burst_order == 0) {
            return false;
        }
        $order_goods_num = model('app\common\model\order\OrderGoodsModel')->where(['order_id' => $order_id])->sum('num');
        $from_user = model('app\common\model\User')->lock(true)->find($user_id);;
        $from_user_group_id = $from_user->group_id;
        $from_user_relation = model('app\common\model\UserRelationModel')->lock(true)->where(['user_id' => $user_id])->find();
//        $from_user_share_earnings = \app\common\model\ShareEarningsModel::get(['group_id' => $from_user_group_id]);
        if(!$from_user_relation) {
            return false;
        }

        // 父级存在,进行分销处理
        if($from_user_relation->p_user_id > 0) {
            $to_user = model('app\common\model\User')->lock(true)->find($from_user_relation->p_user_id);
            $to_user_relation = model('app\common\model\UserRelationModel')->lock(true)->where(['user_id' => $from_user_relation->p_user_id])->find();
            $to_user_group_id = $to_user->group_id;
            if($to_user && $to_user_relation && $to_user_group_id > 1) {
                // 父级收益比例数据
                //num 任务量(箱)
                //recommend 推荐奖
                $to_user_share_earnings = \app\common\model\ShareEarningsModel::get(['group_id' => $to_user_group_id]);
                if($to_user_share_earnings) {
                    // 目标订单金额
                    $order = model('app\common\model\order\OrderModel')->get($order_id);
                    $amount = $order->pay_price;
                    $memo = '佣金[';
                    // 佣金
                    $brokerage = 0;
                    // 推荐奖
                    if($from_user_group_id >= 1) {
                        $recommend = $to_user_share_earnings->recommend;
                        $recommend = $recommend * $order_goods_num;
                        $brokerage += $recommend;
                        $memo .= "推荐奖({$recommend})";
                    }
                    $memo .=']';
                    if($brokerage > 0) {
                        $create_arr = [
                            'mold' => 'order',
                            'mold2' => 'brokerage',
                            'from_user_group_id' => $from_user_group_id,
                            'from_user_id' => $from_user->id,
                            'to_user_group_id' => $to_user_group_id,
                            'to_user_id' => $to_user->id,
                            'order_id' => $order_id,
                            'amount' => $amount,
                            'brokerage' => $brokerage,
                            'createtime' => time(),
                        ];
                        // 创建佣金记录
                        $user_brokerage_log_id = model('app\common\model\UserBrokerageLogModel')->insertGetId($create_arr);
                        $create_arr['id'] = $user_brokerage_log_id;
                        $create_arr['memo'] = $memo;
                        // 增加佣金
                        \app\common\model\User::money($brokerage, $to_user->id, $memo, JsonEn($create_arr));
                    }
                }

                // 上级累计升级处理
                $to_user_num = $to_user_relation->num + $order_goods_num;
                $to_user_relation->num = $to_user_num;
                // 计算等级, 并过滤手动更改等级的用户
                $upgrade_to_user_share_earnings = model('app\common\model\ShareEarningsModel')
                    ->where('num','<=',$to_user_num)
                    ->order('num','desc')
                    ->find();
                // 如果计算出来的等级大于用户当前的等级, 才做修改
                if($upgrade_to_user_share_earnings && $upgrade_to_user_share_earnings->group_id > $to_user_group_id) {
                    $to_user_group_id = $upgrade_to_user_share_earnings->group_id;
                }
                $to_user->group_id = $to_user_group_id;
                $to_user->save();
                $to_user_relation->group_id = $to_user_group_id;
                $to_user_relation->save();
            }
        }

        // 下单人累计升级处理
        $num = $from_user_relation->num + $order_goods_num;
        $from_user_relation->num = $num;
        // 计算等级, 并过滤手动更改等级的用户
        $upgrade_from_user_share_earnings = model('app\common\model\ShareEarningsModel')
            ->where('num','<=',$num)
            ->order('num','desc')
            ->find();
        // 如果计算出来的等级大于用户当前的等级, 才做修改
        if($upgrade_from_user_share_earnings && $upgrade_from_user_share_earnings->group_id > $from_user_group_id) {
            $from_user_group_id = $upgrade_from_user_share_earnings->group_id;
        }
        $from_user->group_id = $from_user_group_id;
        $from_user->save();
        $from_user_relation->group_id = $from_user_group_id;
        $from_user_relation->save();
    }


    /**
     * 佣金记录分页列表
     *
     * @param string $start_time 开始时间
     * @param string $end_time 结束时间
     * @param int $page 页码
     * @param int $limit 每页数据
     */
    public function getPageList($params, $user_id, $page = 1, $limit = 10)
    {
        extract($params);

        try {
            $where = [
                'mold2' => 'brokerage',
                'to_user_id' => $user_id,
            ];
            $start_time = empty($start_time)?strtotime(datetime(time(),'Y-m-1')):strtotime($start_time);
            $end_time = empty($end_time)?strtotime('+1 day'):strtotime('+1 day',strtotime($end_time));
            $where['createtime'] = ['between',[$start_time,$end_time]];

            $field = ['id','mold','mold2','from_user_group_id','from_user_id','to_user_group_id','to_user_id','amount','brokerage','createtime'];
            $list = $this
                ->with([
                    'fromuser' => function($query){
                        $query->field('id,nickname,avatar');
                    },
                    'fromusergroup' => function($query){
                        $query->field('id,name');
                    },
//                    'touser' => function($query){
//                        $query->field('id,nickname,avatar');
//                    },
//                    'tousergroup' => function($query){
//                        $query->field('id,name');
//                    },
                ])
                ->field($field)
                ->where($where)
                ->order('createtime', 'desc')
                ->paginate($limit, false, ['page' => $page]);

            foreach ($list as $row) {
                $row->createtime = datetime($row->createtime);
                if($row->fromuser) {
                    $row->fromuser->avatar = full_url($row->fromuser->avatar);
                }
            }

            return [
                'code' => 200,
                'msg' => '请求成功',
                'data' => $list
            ];
        }catch (\Exception $e) {
            return [
                'code' => $e->getCode(),
                'msg' => $e->getMessage(),
                'data' => $e->getLine()
            ];
        }
    }




    public function fromuser(){
        return $this->belongsTo('app\common\model\User','from_user_id','id');
    }


    public function touser(){
        return $this->belongsTo('app\common\model\User','to_user_id','id');
    }


    public function fromusergroup(){
        return $this->belongsTo('app\common\model\UserGroup','from_user_group_id','id');
    }


    public function tousergroup(){
        return $this->belongsTo('app\common\model\UserGroup','to_user_group_id','id');
    }


}